<?php declare(strict_types=1);

namespace Zyucv7\Core\Router;

use Zyucv7\Core\Router\RouterException;
use Zyucv7\Core\Web\Request;

/**
 * 路由 分发器
 */

 class Dispatcher
{
    private $handler;
    private $request;

    public function __construct($handler, Request $request)
    {
        $this->handler = $handler;
        $this->request = $request;
    }

    // 执行路由分发
    public function execute()
    {
        if (is_callable($this->handler)) {
            call_user_func($this->handler, $this->request);
            return;
        }

        if(!is_string($this->handler)) {
            throw RouterException::message('Dispatcher handler must be callable or string');
        }

        // Assume format 'Class@method'
        if (strpos($this->handler, '@') === false) {
            throw RouterException::message('Dispatcher Invalid handler format');
        }

        list($class, $method) = explode('@', $this->handler);

        if (!class_exists($class)) {
            throw RouterException::message('Dispatcher Class not found');
        }

        $controller = new $class();
        if (!method_exists($controller, $method)) {
            throw RouterException::message("Method $method not found in $class");
        }

        call_user_func([$controller, $method], $this->request);
    }
}